/*
 * Copyright (c) 2015  南京瑞玥科技有限公司. All Rights Reserved.
 */
package com.kecheng.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.kecheng.com.yx.util.WeixinUtil;

/**
 * @author 雷杨
 * @date 2015-04-09
 */
public class DownLoad {

	/**
	 * 根据tikect获取二维码并且下载下来
	 */
	public static String downloadCode(String url1, String openid, String save) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		String filePath = null;
		// 拼接请求地址
		String requestUrl = url1;
		try {
			// 存储的路径
			String savePath = save;
			URL url = new URL(requestUrl);
			// HTTP协议

			HttpURLConnection httpUrlConn = (HttpURLConnection) url
					.openConnection();
			System.out.print("httpUrlConn:" + httpUrlConn);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod("GET");

			// // 注意编码格式，防止中文乱码

			File flod = new File(savePath);
			if (!flod.exists()) {
				flod.mkdirs();
			}

			if (!savePath.endsWith("/")) {
				savePath += "/";
			}
			// 根据内容类型获取扩展名
			String content_type = httpUrlConn.getHeaderField("Content-Type");
			System.out.println("conten1t_type:" + content_type);
			if (!content_type.contains("json")) {// 返回的是文件
				String fileExt = content_type.substring(content_type
						.indexOf("/") + 1);
				System.out.println("fileExt:" + fileExt);
				// 将mediaId作为文件名
				filePath = openid + "." + fileExt;


				InputStream inputStream = httpUrlConn.getInputStream();
				BufferedInputStream bis = new BufferedInputStream(inputStream);
				FileOutputStream fos = new FileOutputStream(new File(savePath,
						filePath));
				byte[] buf = new byte[8096];
				int size = 0;
				while ((size = bis.read(buf)) != -1)
					fos.write(buf, 0, size);
				fos.close();
				bis.close();

				// 获取图片的md5值
				httpUrlConn.disconnect();
				String info = String.format("下载媒体文件成功，filePath=" + filePath);
				System.out.println(info);
				return filePath;
			} else {// 返回错误信息
				StringBuffer buffer = new StringBuffer();
				InputStream inputStream = httpUrlConn.getInputStream();
				InputStreamReader inputStreamReader = new InputStreamReader(
						inputStream, "utf-8");
				BufferedReader bufferedReader = new BufferedReader(
						inputStreamReader);

				String str = null;
				while ((str = bufferedReader.readLine()) != null) {
					buffer.append(str);
				}
				bufferedReader.close();
				inputStreamReader.close();
				// 释放资源
				inputStream.close();
				inputStream = null;
				httpUrlConn.disconnect();
				System.out.println(buffer);
				JSONObject jsonObject = JSONObject
						.fromObject(buffer.toString());
				returnMap.put("state", jsonObject.get("errcode"));
				returnMap.put("msg", jsonObject.get("errmsg"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			filePath = null;
			returnMap.put("state", 1);
			returnMap.put("msg", "下载媒体文件失败" + e.getMessage());
		}

		return null;
	}

	//新增临时素材接口
	public static JSONObject addSucai(String fileType, String filePath) throws Exception {  
        String result = null;  
        File file = new File(filePath);  
        if (!file.exists() || !file.isFile()) {  
            throw new IOException("文件不存在");  
        }  
        /** 
        * 第一部分 
        */  
        //String accessToken = WeixinUtil.getAccessToken("wx4fbdc6894080873b","46fb45d73a350c93fe6dedf801013b1d").getToken();
        String accessToken = WeixinUtil.getAccessToken().getToken();
        URL urlObj = new URL("https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+ accessToken + "&type="+fileType);
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();  
        con.setRequestMethod("POST"); // 以Post方式提交表单，默认<a href="https://www.baidu.com/s?wd=get&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1Y3ny7bnjnzmHmYPHnYPWK90ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EnHT4PWm4rHbLPHbkPW63PjmzPs" target="_blank" class="baidu-highlight">get</a>方式  
        con.setDoInput(true);  
        con.setDoOutput(true);  
        con.setUseCaches(false); // post方式不能使用缓存  
        // 设置请求头信息  
        con.setRequestProperty("Connection", "Keep-Alive");  
        con.setRequestProperty("Charset", "UTF-8");  
        // 设置边界  
        String BOUNDARY = "----------" + System.currentTimeMillis();  
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);  
        // 请求正文信息  
        // 第一部分：  
        StringBuilder sb = new StringBuilder();  
        sb.append("--"); // 必须多两道线  
        sb.append(BOUNDARY);  
        sb.append("\r\n");  
        sb.append("Content-Disposition: form-data;name=\"file\";filename=\""+ file.getName() + "\"\r\n"); 
        sb.append("Content-Type:application/octet-stream\r\n\r\n");  
        byte[] head = sb.toString().getBytes("utf-8");  
        // 获得输出流  
        OutputStream out = new DataOutputStream(con.getOutputStream());  
        // 输出表头  
        out.write(head);  
        // 文件正文部分  
        // 把文件已流文件的方式 推入到url中  
        DataInputStream in = new DataInputStream(new FileInputStream(file));  
        int bytes = 0;  
        byte[] bufferOut = new byte[1024];  
        while ((bytes = in.read(bufferOut)) != -1) {  
        out.write(bufferOut, 0, bytes);  
        }  
        in.close();  
        // 结尾部分  
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线  
        out.write(foot);  
        out.flush();  
        out.close();  
        StringBuffer buffer = new StringBuffer();  
        BufferedReader reader = null;  
        try {  
        // 定义BufferedReader输入流来读取URL的响应  
        reader = new BufferedReader(new InputStreamReader(con.getInputStream()));  
        String line = null;  
        while ((line = reader.readLine()) != null) {  
        //System.out.println(line);  
        buffer.append(line);  
        }  
        if(result==null){  
        result = buffer.toString();  
        }  
        } catch (IOException e) {  
        System.out.println("发送POST请求出现异常！" + e);  
        e.printStackTrace();  
        throw new IOException("数据读取异常");  
        } finally {  
        if(reader!=null){  
        reader.close();  
        }  
        }  
        System.err.println("上传完毕result：："+result);
        //JSONObject jsonObj =new JSONObject(result);
        JSONObject jsonObj = JSONObject.fromObject(result);
        return jsonObj;  
    }
	
	//新增永久素材
	public static String addYongjiu(String fileType, String filePath) throws Exception {  
        String result = null;  
        File file = new File(filePath);  
        if (!file.exists() || !file.isFile()) {  
            throw new IOException("文件不存在");  
        }  
        /** 
        * 第一部分 
        */  
        String accessToken = WeixinUtil.getAccessToken().getToken();
        URL urlObj = new URL("https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+ accessToken + "&type="+fileType); 
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();  
        con.setRequestMethod("POST"); // 以Post方式提交表单，默认<a href="https://www.baidu.com/s?wd=get&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1Y3ny7bnjnzmHmYPHnYPWK90ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EnHT4PWm4rHbLPHbkPW63PjmzPs" target="_blank" class="baidu-highlight">get</a>方式  
        con.setDoInput(true);  
        con.setDoOutput(true);  
        con.setUseCaches(false); // post方式不能使用缓存  
        // 设置请求头信息  
        con.setRequestProperty("Connection", "Keep-Alive");  
        con.setRequestProperty("Charset", "UTF-8");  
        // 设置边界  
        String BOUNDARY = "----------" + System.currentTimeMillis();  
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);  
        // 请求正文信息  
        // 第一部分：  
        StringBuilder sb = new StringBuilder();  
        sb.append("--"); // 必须多两道线  
        sb.append(BOUNDARY);  
        sb.append("\r\n");  
        sb.append("Content-Disposition: form-data;name=\"file\";filename=\""+ file.getName() + "\"\r\n"); 
        sb.append("Content-Type:application/octet-stream\r\n\r\n");  
        byte[] head = sb.toString().getBytes("utf-8");  
        // 获得输出流  
        OutputStream out = new DataOutputStream(con.getOutputStream());  
        // 输出表头  
        out.write(head);  
        // 文件正文部分  
        // 把文件已流文件的方式 推入到url中  
        DataInputStream in = new DataInputStream(new FileInputStream(file));  
        int bytes = 0;  
        byte[] bufferOut = new byte[1024];  
        while ((bytes = in.read(bufferOut)) != -1) {  
        out.write(bufferOut, 0, bytes);  
        }  
        in.close();  
        // 结尾部分  
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线  
        out.write(foot);  
        out.flush();  
        out.close();  
        StringBuffer buffer = new StringBuffer();  
        BufferedReader reader = null;  
        try {  
        // 定义BufferedReader输入流来读取URL的响应  
        reader = new BufferedReader(new InputStreamReader(con.getInputStream()));  
        String line = null;  
        while ((line = reader.readLine()) != null) {  
        //System.out.println(line);  
        buffer.append(line);  
        }  
        if(result==null){  
        result = buffer.toString();  
        }  
        } catch (IOException e) {  
        System.out.println("发送POST请求出现异常！" + e);  
        e.printStackTrace();  
        throw new IOException("数据读取异常");  
        } finally {  
        if(reader!=null){  
        reader.close();  
        }  
        }  
        System.err.println("上传完毕result：："+result);
        //JSONObject jsonObj =new JSONObject(result);
        JSONObject jsonObj = JSONObject.fromObject(result);
        return jsonObj.getString("media_id");  
    }
	


}
